package sskj.regulatory.presentation.screen.register

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Message
import android.text.*
import android.text.style.AbsoluteSizeSpan
import android.view.View
import android.widget.Toast
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.vondear.rxtools.RxKeyboardTool
import com.vondear.rxtools.RxRegTool
import kotlinx.android.synthetic.main.fragment_register.view.*
import kotlinx.android.synthetic.main.identifying_code_layout.view.*
import sskj.regulatory.R
import sskj.regulatory.domain.entity.user.UserEntity
import sskj.regulatory.presentation.base_mvp.base.BaseFragment
import sskj.regulatory.presentation.screen.registeCaptcha.RegisterCaptchaFragment
import sskj.regulatory.presentation.screen.sitevideo.siteveiw.SiteViewFragment
import sskj.regulatory.presentation.utils.ST
import sskj.regulatory.presentation.utils.delegates.bundleWith
import sskj.regulatory.ribble.presentation.utils.extensions.log
import java.util.*
import javax.inject.Inject

class RegisterFragment : BaseFragment<RegisterContract.View, RegisterContract.Presenter>(), RegisterContract.View {

    private val TAG = "RegisterFragment"

    var userEntity: UserEntity? = UserEntity()

    companion object {
        fun getBundle(userEntity: UserEntity) = "userEntity" bundleWith userEntity
    }

    @Inject
    lateinit var mPresenter: RegisterPresenter

    override fun injectDependencies() = activityComponent.inject(this)

    override fun initPresenter() = mPresenter

    override val layoutResId: Int = R.layout.fragment_register

    override fun onBackPressed(): Boolean = true

    override fun initView() {
        refresh()
        initHitSize()
        initEvent()
        initTopBar()
    }

    /**
     * 设置提示文字
     */
    @SuppressLint("ResourceAsColor")
    private fun initHitSize() {

        val ss = SpannableString("请输入手机号码")
        val ass = AbsoluteSizeSpan(16, true)
        ss.setSpan(ass, 0, ss.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        mCacheView.etPhone.hint = SpannedString(ss)
        mCacheView.etPhone.setHintTextColor(R.color.qmui_config_color_50_pure_black)
        mCacheView.messageTv.visibility = View.GONE

        RxKeyboardTool.showSoftInput(context, mCacheView.etPhone)
    }

    private fun refresh() {
        mCacheView.cleanPhone.visibility = View.GONE
        mCacheView.messageTv.visibility = View.GONE
        mCacheView.registeButton.isEnabled = false
        this.userEntity = UserEntity()
        mCacheView.etPhone.setText("")
    }

    private fun initTopBar() {
        mCacheView.rTopBar.addLeftBackImageButton().setOnClickListener {
            popBackStack()
        }
    }

    private fun initEvent() {
        mCacheView.etPhone.setOnFocusChangeListener { _, b ->
            when (b) {
                false -> RxKeyboardTool.hideSoftInput(getActivity())
            }
        }

        mCacheView.etPhone.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

                if (s.length === 0) return

                var sb = StringBuilder()

                for (i in 0 until s.length) {
                    if (i != 3 && i != 8 && s[i] === ' ') {
                        continue
                    } else {
                        sb.append(s[i])
                        if ((sb.length == 4 || sb.length == 9) && sb[sb.length - 1] != ' ') {
                            sb.insert(sb.length - 1, ' ')
                        }
                    }
                }
                if (sb.toString() != s.toString()) {
                    var index = start + 1
                    if (sb[start] == ' ') {
                        if (before === 0) {
                            index++
                        } else {
                            index--
                        }
                    } else {
                        if (before === 1) {
                            index--
                        }
                    }
                    mCacheView.etPhone.setText(sb.toString())
                    mCacheView.etPhone.setSelection(index)
                }

            }

            override fun afterTextChanged(s: Editable) {

                when (RxRegTool.isMobile(s.replace(Regex(" "), ""))) {
                    true -> {
                        mPresenter.isRegister(s.replace(Regex(" "), ""))
                    }
                    else -> {
                        mCacheView.messageTv.text = "手机号码错误,请重新输入。"
                        mCacheView.registeButton.isEnabled = false
                    }
                }

                if (!TextUtils.isEmpty(s) && mCacheView.cleanPhone.visibility == View.GONE) {
                    mCacheView.cleanPhone.visibility = View.VISIBLE
                    mCacheView.messageTv.visibility = View.GONE
                } else if (TextUtils.isEmpty(s)) {
                    mCacheView.cleanPhone.visibility = View.GONE
                }

            }
        })

        mCacheView.registeButton.setOnClickListener { mPresenter.sendVCode(mCacheView.etPhone.text.replace(Regex(" "), "")) }

        mCacheView.cleanPhone.setOnClickListener { mCacheView.etPhone.setText("") }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) { //返回的时候
            this.refresh(); //调用方法刷新
        }
    }

    override fun showRegisterYes() {
        mCacheView.registeButton.isEnabled = true
    }

    override fun showRegisterNo() {
        mCacheView.messageTv.text = "该手机号已经注册,请重新输入。"
        mCacheView.messageTv.visibility = View.VISIBLE
        mCacheView.etPhone.setText("")
        mCacheView.registeButton.isEnabled = false
    }


    override fun sendOk(phone: String, vCode: String) {
        log("$TAG:$vCode")

        activity.tipDialog?.dismiss()
        activity.tipDialog = createDialog("发送成功!", QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
        activity.tipDialog?.show()

        view?.postDelayed({

            activity.tipDialog?.dismiss()
            userEntity?.username = phone
            userEntity?.phone = phone
            userEntity?.vCode = vCode
            userEntity?.time = Date()

            var registerCaptchaFragment = RegisterCaptchaFragment()
            registerCaptchaFragment.arguments = RegisterFragment.getBundle(userEntity!!)
            startFragment(registerCaptchaFragment)

        }, 1000)
    }

    private fun createDialog(message: String, type: Int): QMUITipDialog = QMUITipDialog.Builder(context)
            .setIconType(type)
            .setTipWord(message)
            .create()

    override fun sendError(errorMessage: String?) {
        activity.tipDialog?.dismiss()
        activity.tipDialog = createDialog("发送失败!", QMUITipDialog.Builder.ICON_TYPE_FAIL)
        activity.tipDialog?.show()

        view?.postDelayed({
            activity.tipDialog?.dismiss()
        }, 1000)
    }

    override fun sendLoading() {
        activity.tipDialog = createDialog("发送中", QMUITipDialog.Builder.ICON_TYPE_LOADING)
        activity.tipDialog?.show()
    }


    override fun sendTimeNo() {
        QMUIDialog.MessageDialogBuilder(getActivity()).setTitle("提示信息").setMessage("你还需要等待 ${RegisterCaptchaFragment.along} 秒才能再次发送。")
                .addAction("确定") { dialog, _ -> dialog.dismiss() }
                .create(R.style.QMUI_Dialog).show()
    }

    override fun showError(message: String?) {
        activity.tipDialog = createDialog("系统出错", QMUITipDialog.Builder.ICON_TYPE_FAIL)
        activity.tipDialog?.show()

        view?.postDelayed({
            activity.tipDialog?.dismiss()
        }, 1500)
    }
}